package com.ojoin.trade.common.autoconfig.base;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.collect.Maps;
import com.ojoin.trade.common.autoconfig.api.IChangeListener;
import com.ojoin.trade.common.autoconfig.api.IChangeable;
import com.ojoin.trade.common.autoconfig.api.IChangeableConfig;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.web.domain.Dict;
import com.ojoin.trade.common.web.domain.User;
import com.ojoin.trade.common.web.service.DictService;

/**
 * 配置基类
 */
@Component
public class ChangeableConfig extends Config implements IChangeableConfig {
	
  private static final  Logger log = LoggerFactory.getLogger(ChangeableConfig.class);
  
  private final IChangeable eventBus;
  
  
  private DictService dictService;
  @Autowired
  public ChangeableConfig(DictService dictService ) {
    this.eventBus = new EventBus(this);
    
    this.dictService=dictService;
	
	try {
		
        copyOf(load());
       
    } catch (Exception e) {
    	
      copyOf(new byte[0]);
      
    }
    
  }

	private Map<String, String> load() {

		Dict queryDict = new Dict();
		queryDict.setCreateBy(new User(0));
		queryDict.setType("online.config");

		List<Dict> dicts = dictService.queryList(queryDict);

		Map<String, String> param = Maps.newHashMap();
		for (Dict dict : dicts) {
			param.put(dict.getLabel(), dict.getValue());
		}

		return param;
	}
  
  @Override
  public String getName() {
    return "";
  }

  public void addListener(IChangeListener listener) {
    eventBus.addListener(listener);
  }

  public void addListener(IChangeListener listener, boolean loadAfterRegister) {
    eventBus.addListener(listener, loadAfterRegister);
  }

  public void removeListener(IChangeListener listener) {
    eventBus.removeListener(listener);
  }

  public void notifyListeners() {
	  Map<String,String> newP=load();
	  if(isChanged(mapToByte(newP))){
		  copyOf(newP);
		  eventBus.notifyListeners();
	  }
  }


  /**
   * 判断新接收到的数据和以前相比是否发生了变化
   *
   * @param now 新数据
   * @return 逐字节对比，不一样就返回true
   */
  public boolean isChanged(byte[] now) {
    if (now == null) {
      return true;
    }
    byte[] old = getContent();
    
    LogUtils.info(log,"change detecting\nbefore:\n{}\n\nafter:\n{}\n",new String(old),new String(now));
    return !Arrays.equals(now, old);
  }
  
	
}
